/*
 * File:   socket_server.c
 * Author: onteria_
 *
 * Created on April 30, 2011, 7:11 AM
 */

#include <sys/types.h>
#include <ctype.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h> 
#include <time.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <miko/defines.h>
#include <miko/socket.h>

#include "threaded_server.h"
#include "config_file.h"

void cleanup(int signum);

void cleanup(int signum)
{
    if(server_ipv4) {
        close(server_ipv4);
    }    
    if(server_ipv6) {
    	close(server_ipv6);
    }
    pthread_exit(NULL);
    return;
}

int main (int argc, char *argv[]) {
    
    signal(SIGINT, cleanup);      /* now handle SIGTERM and SIGINT */    
    signal(SIGTERM, cleanup);

    config_file = parse_config("miko.cfg");
    
    if(miko_setup_server(config_file.ipv6) != MIKO_SUCCESS) {
    	return MIKO_ERROR;
    }

    while(1) {
    	if(server_ipv4) {
    		miko_run_server(server_ipv4, &process_connection, MIKO_IPV4);
    	}
    	if(server_ipv6) {
    		miko_run_server(server_ipv6, &process_connection, MIKO_IPV6);
    	}
    	sleep(1);
    }

    return 0;
}
